
<template>
  <emer-container>
    <a-row :gutter="10" style="height: 100%">
      <!-- 左侧表格 -->
      <a-col :span="14" style="height: 100%">
        <emer-card
          filled
          :bodyStyle="{ width: '100%', height: '100%', padding: 0 }"
        >
          <!-- 表格顶部搜索栏 -->
          <div class="operate-bar">
            <a-row type="flex">
              <a-col :flex="1">
                <a-form-model
                  layout="inline"
                  :colon="false"
                  :model="searchForm"
                >
                  <a-form-model-item label="文书属性">
                    <a-select
                      v-model="searchForm.typeId"
                      class="search-select"
                      @change="onSearchTypeChange"
                      placeholder="请选择文书属性"
                    >
                      <a-select-option :value="null">全部</a-select-option>
                      <a-select-option
                        v-for="(option, index) in dict.attrOptions"
                        :key="index"
                        :value="option.id"
                      >
                        {{ option.value }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <a-form-model-item label="搜索">
                    <a-input-search
                      v-model="searchForm.condit"
                      placeholder="检查项、检查内容关键字"
                      class="search-input"
                      @search="onSearch"
                    />
                  </a-form-model-item>
                </a-form-model>
              </a-col>
              <a-col>
                <a-space class="media-padding">
                  <a-button @click="handleDelete">删除</a-button>
                  <a-button @click="handleClickAdd" type="primary"
                    >新增</a-button
                  >
                  <a-button @click="handleDownload('bulk')" type="primary"
                    >批量下载</a-button
                  >
                </a-space>
              </a-col>
            </a-row>
          </div>

          <!-- 表格 -->
          <div class="table-wrap" ref="tableWrap">
            <a-table
              class="emer-scroll-table"
              :columns="columns"
              rowKey="id"
              :data-source="data"
              :rowClassName="rowClassName"
              :customRow="customRow"
              :row-selection="{
                selectedRowKeys: this.selectedRowKeys,
                onChange: onSelectChange,
              }"
              :pagination="false"
              :loading="state.listLoading"
              :scroll="tableScroll"
              bordered
            >
            </a-table>
          </div>

          <!-- 分页 -->
          <div class="pagination-wrap">
            <a-pagination
              class="emer-pagination"
              size="small"
              :current="pagination.current"
              :total="pagination.total"
              :page-size="pagination.pageSize"
              :show-total="(total) => `共${total}条`"
              @change="onPageChange"
              @showSizeChange="onPageSizeChange"
            />
          </div>
        </emer-card>
      </a-col>

      <!-- 右侧表单 -->
      <a-col :span="10" style="height: 100%">
        <emer-card filled flexLayout>
          <span slot="title">文书详情</span>
           <span
            v-show="editMode === 'detail'"
            class="card-action"
            slot="extra"
            @click="handleClickEdit">
            编辑
          </span>
          <scrollbar
            wrapClass="overflowXHidden"
            class="scrollbar-bar-outside"
            style="height: 100%"
          >
          <div ref="editorWrap" class="card-main-content">
            <!-- 详情 -->
            <div
                v-show="editMode === 'detail'"
                class="detail-content"
              >
                <a-row :gutter="30">
                  <div style="overflow: hidden;">
                    <a-col :span="24" :xxl="12">
                      <div class="detail-item">
                        <div class="detail-item-label">文书名称</div>
                        <div class="detail-item-val">
                          {{ selectedRow && selectedRow.fileName || '' }}
                        </div>
                      </div>
                    </a-col>
                    <a-col :span="24" :xxl="12">
                      <div class="detail-item">
                        <div class="detail-item-label">文书属性</div>
                        <div class="detail-item-val">
                          {{ selectedRow && (selectedRow.attri || {}).value || '' }}
                        </div>
                      </div>
                    </a-col>
                  </div>

                  <div style="overflow: hidden;">
                    <a-col :span="24">
                      <div class="detail-item">
                        <div class="detail-item-label">文书内容</div>
                        <div class="detail-item-val">
                          <div v-html="selectedRow.content"></div>
                        </div>
                      </div>
                    </a-col>
                  </div>
                </a-row>
              </div>
            <!-- 编辑表单 -->
            <a-form-model
              v-show="editMode === 'edit'"
              ref="editForm"
              class="edit-form"
              layout="inline"
              hideRequiredMark
              :colon="false"
              :model="editForm"
              :rules="editFormRules"
            >
              <a-row :gutter="30">
                <a-col :span="14">
                  <a-form-model-item label="文书名称" prop="fileName">
                    <a-input
                      ref="editFormName"
                      v-model="editForm.fileName"
                      placeholder="请填写文书名称"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="10">
                  <a-form-model-item label="文书属性" prop="attri">
                    <a-select
                      v-model="editForm.attri"
                      placeholder="请选择文书属性"
                    >
                      <a-select-option
                        v-for="(option, index) in dict.attrOptions"
                        :key="index"
                        :value="option.id"
                      >
                        {{ option.value }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-form-model-item label="文书内容" prop="content">
                <!-- <editor
                  id="tinymce"
                  style="width: calc(100% - 2px)"
                  v-model="editForm.content"
                  api-key="no-api-key"
                  :init="{
                    height: 490,
                    language: 'zh_CN',
                  }"
                /> -->

                <editor
                  ref="execeditor"
                  :heights="editorHeight"
                  :content.sync="editForm.content"
                />
              </a-form-model-item>
            </a-form-model>
          </div>
          </scrollbar>
          <!-- 底部操作按钮 -->
          <div slot="footer" class="edit-action">
            <a-space>
              <a-button @click="handleCancel"> 取消 </a-button>
              <a-button
                :loading="state.saveLoading"
                @click="handleSave"
                type="primary"
              >
                保存
              </a-button>
              <a-button
                v-show="isShowDownload"
                :loading="state.downloading"
                @click="handleDownload('single')"
                type="primary"
              >
                下载文书
              </a-button>
            </a-space>
          </div>
        </emer-card>
      </a-col>
    </a-row>
  </emer-container>
</template>

<script>
// import debounce from 'lodash/debounce'

import {
  getDocumentList,
  fetchDocumentAdd,
  fetchDocumentUpdate,
  fetchDocumentDelete,
  fetchDocumentDownload,
  fetchDocumentDownloadBatch
} from '@/api/company/content/document'
import { getDictionaryByType } from '@/api/common/business'

// import Editor from '@tinymce/tinymce-vue'
import Editor from '@/components/wangeditor'
import { on, off } from '@/libs/util.dom'
const columns = [
  {
    title: '文书名称',
    dataIndex: 'fileName',
    key: 'fileName',
    width: 300,
    ellipsis: true
  },
  {
    title: '文书属性',
    dataIndex: 'attri.value',
    width: 200,
    ellipsis: true
  },
  {
    title: '更新用户',
    dataIndex: 'userName',
    width: 200,
    ellipsis: true
  },
  {
    title: '更新时间',
    dataIndex: 'updatedTime',
    width: 170,
    ellipsis: true
  }
]
function download (data, type = null, fileName) {
  console.log(type)
  const blob = new Blob([data], type)
  var timestamp = (new Date()).valueOf()
  if (!fileName) {
    fileName = timestamp + '.zip'
  }
  if ('download' in document.createElement('a')) { // 非IE下载
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = window.URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    window.URL.revokeObjectURL(elink.href) // 释放URL 对象
    document.body.removeChild(elink)
  } else { // IE10+下载
    navigator.msSaveBlob(blob, fileName)
  }
}
export default {
  name: 'company-announcement-document',
  components: {
    Editor
  },
  data () {
    // 节流控制，防止频繁请求
    // this.fetchEnterpriseByName = debounce(this.fetchEnterpriseByName, 800)
    return {
      editMode: 'detail',
      firstLoadList: true,
      searchForm: {
        typeId: null,
        condit: undefined
      },
      data: [],
      selectedRow: {},
      selectedRowKeys: [],
      editForm: {
        fileName: undefined,
        attri: undefined,
        userName: undefined,
        updatedTime: undefined,
        content: undefined
      },
      editFormRules: {
        fileName: [
          { required: true, message: '请填写文书名称', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请填写文书内容', trigger: 'blur' }
        ],
        attri: [{ required: true, message: '请选择文书属性', trigger: 'blur' }]
      },
      dict: {
        attrOptions: []
      },
      columns,
      pagination: {
        current: 1,
        pageSize: 15,
        total: 0
      },
      state: {
        downloading: false,
        listLoading: false,
        saveLoading: false,
        enterpriseFetching: false
      },
      loading: false,
      tableScroll: { x: 940, y: 0 },
      isShowDownload: false,
      editorHeight: 0,
      downLoadBatchList: []
    }
  },
  activated () {
    this.heightWatch()
  },
  created () {
    this.fetchDict()
    this.fetchList()
  },
  mounted () {
    this.heightWatch()
    on(window, 'resize', () => {
      this.heightWatch()
    })
  },
  destroyed () {
    off(window, 'resize')
  },
  watch: {
    editorHeight (val) {
      this.editorHeight = val
    }
  },
  methods: {
    // 获取编辑器内容
    getContent (content) {
      this.editForm.content = content
    },
    // 动态获取表格、富文本高度计算
    heightWatch () {
      this.tableScroll.y = this.$refs.tableWrap.offsetHeight - 56
      this.editorHeight = this.$refs.editorWrap.offsetHeight - 78
    },
    // 获取列表
    fetchList (isRestore = false) {
      if (isRestore) {
        this.resetPagination()
      }
      this.state.listLoading = true
      getDocumentList({
        ...this.searchForm,
        page: this.pagination.current,
        pageSize: this.pagination.pageSize
      })
        .then((res) => {
          const resData = res.data
          this.data = resData.data || []
          this.pagination.total = resData.total
          if (this.firstLoadList) {
            this.setDefaultSelectedRow()
            this.firstLoadList = false
          }
        })
        .finally(() => {
          this.state.listLoading = false
        })
    },
    // 请求字典数据
    fetchDict () {
      // 文书属性
      getDictionaryByType({
        code: 'file_attri'
      }).then((res) => {
        const resData = res.data
        if (resData) {
          this.dict.attrOptions = resData
        }
      })
    },
    // 检索
    onSearch () {
      this.fetchList()
    },
    // 选择文书属性
    onSearchTypeChange () {
      this.onSearch()
    },
    // 点击新增按钮
    handleClickAdd () {
      this.isShowDownload = false
      this.resetFields()
      this.selectedRow = null
      this.selectedRowKeys = []
      setTimeout(() => {
        this.$refs.editFormName.focus()
      }, 100)
    },
    // 点击编辑
    handleClickEdit () {
      this.editMode = 'edit'
      // this.resetFields()
      // this.setFormDataFromTableRow()
      // setTimeout(() => {
      //   this.$refs.editFormNum.focus()
      // }, 100)
    },
    // 清空表单数据
    resetFields () {
      this.$refs.editForm.resetFields()
      this.editForm.id = undefined
      this.editForm.fileName = ''
      this.editForm.attri = ''
      this.editForm.content = ''
      this.$refs.editForm.clearValidate()
    },
    // 保存
    handleSave () {
      this.editForm.content = this.$refs.execeditor.getHtml()
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          if (this.editForm.id) {
            fetchDocumentUpdate(this.editForm)
              .then((res) => {
                this.fetchList()
                this.$message.success('文书更新成功')
              })
              .finally(() => {
                this.state.saveLoading = false
              })
          } else {
            fetchDocumentAdd(this.editForm)
              .then((res) => {
                this.resetFields()
                this.firstLoadList = true
                this.fetchList(true)
                this.$message.success('文书新增成功')
              })
              .finally(() => {
                this.state.saveLoading = false
              })
          }
        } else {
          return false
        }
      })
    },
    // 删除
    handleDelete () {
      if (this.selectedRowKeys.length === 0) {
        return this.$message.warning('请选择需删除项目')
      }
      this.$confirm({
        title: '此操作将永久删除所选项, 是否继续?',
        onOk: () => {
          fetchDocumentDelete(this.selectedRowKeys).then((res) => {
            this.$message.success('删除成功')
            this.firstLoadList = true
            this.fetchList()
          })
        },
        onCancel () {
          console.log('Delete Cancel')
        }
      })
    },
    // 将选中表格行的样式填充表单
    setFormDataFromTableRow () {
      const row = this.selectedRow
      if (row) {
        Object.assign(this.editForm, {
          id: row.id,
          fileName: row.fileName,
          attri: (row.attri || {}).id,
          userName: row.userName,
          updatedTime: row.updatedTime,
          content: row.content
        })
      }
    },
    // 表格行选中
    onSelectChange (selectedRowKeys, selectedRows) {
      this.downLoadBatchList = []
      for (let i = 0; i < selectedRows.length; i++) {
        if (selectedRows[i].fileId) {
          this.downLoadBatchList.push(selectedRows[i].fileId)
        }
      }
      console.log(this.downLoadBatchList)
      this.selectedRowKeys = selectedRowKeys
    },
    // 页码改变
    onPageChange (current) {
      this.pagination.current = current
      this.fetchList()
    },
    resetPagination () {
      this.pagination.current = 1
      this.pagination.pageSize = 15
    },
    // 分页大小改变
    onPageSizeChange (current, pageSize) {
      this.pagination.current = current
      this.pagination.pageSize = pageSize
      this.fetchList()
    },
    // 表格行
    customRow (record, index) {
      return {
        on: {
          click: () => {
            this.editMode = 'detail'
            this.$refs.editForm.clearValidate()
            this.isShowDownload = true
            // this.selectedRowKeys = [record.id]
            this.selectedRow = this.data[index]
            this.setFormDataFromTableRow()
          }
        }
      }
    },
    // 编辑取消
    handleCancel () {
      // this.resetFields()
      this.isShowDownload = false
      this.selectedRowKeys = []
    },
    // 文书下载
    handleDownload (type) {
      if (type === 'single') {
        this.state.downloading = true
        if (this.selectedRow.fileId) {
          fetchDocumentDownload({ file: this.selectedRow.fileId }).then(
            (res) => {
              download(res, { type: 'application/pdf' }, this.selectedRow.fileName + '.pdf')
            }
          ).finally(() => {
            this.state.downloading = false
          }).catch(req => {
            this.$message.warning('下载失败')
            console.log('下载失败', req)
          })
        } else {
          this.$message.warning('文书未保存')
        }
      } else {
        if (this.selectedRowKeys.length < 1) {
          this.$message.warning('请选择需要下载的文书')
        } else {
          fetchDocumentDownloadBatch({ files: this.downLoadBatchList })
            .then((res) => {
              download(res, { type: 'application/zip' })
            })
          this.selectedRow = null
          this.selectedRowKeys = []
        }
      }
    },

    // 默认选中第一行
    setDefaultSelectedRow () {
      const index = 0
      const record = this.data[index]
      this.rowIndex = index
      // this.selectedRowKeys = [record.id]
      this.isShowDownload = true
      this.selectedRow = record
      this.setFormDataFromTableRow()
    },
    // 表格选中样式
    rowClassName (record, index) {
      return this.selectedRow && record.id === this.selectedRow.id
        ? 'ant-table-row-selected'
        : ''
    }
  }
}
</script>

<style lang="scss" scoped>
.operate-bar {
  padding: 7px 10px;
  min-height: 54px;
  .media-padding {
    margin: 10px 0;
  }
  .search-select {
    width: 140px;
  }
  .search-input {
    width: 250px;
  }
}

@media (min-width: 1600px) {
  .operate-bar {
    .media-padding {
      margin: 0;
    }
    .search-select {
      width: 140px;
    }
    .search-input {
      width: 250px;
    }
  }
}

.table-wrap {
  width: 100%;
  height: calc(100% - 54px - 72px);
  padding: 0 10px;
  overflow: hidden;
}

.pagination-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 10px 30px 10px;
}

.card-action {
  font-size: 14px;
  cursor: pointer;
}

.address-tip {
  height: 22px;
  color: #666;
  font-size: 12px;
  line-height: 22px;
}

.map-area {
  position: relative;
  width: 100%;
  margin-top: 20px;
  padding: 32% 50% 32% 50%;
  background-color: $color-bg;
}

.divider-line {
  height: 1px;
  border-bottom: 1px dashed #d7e0ef;
}

.card-main-content {
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
}
.edit-action {
  text-align: right;
  padding: 20px;
}

// ::v-deep .ant-table-selection-column {
//   display: none;
// }

.edit-form {
  ::v-deep &.ant-form-inline {
    .ant-form-item {
      display: flex;
      width: 100%;
      margin-bottom: 20px;
      & > .ant-form-item-control-wrapper {
        flex: 1;
        width: 0;
      }
      & > .ant-form-item-label {
        width: 70px;
        line-height: 36px;
        font-size: 14px;
        font-weight: bold;
        & > label {
          color: #333;
        }
      }
    }
    .ant-form-item-with-help {
      margin-bottom: 0;
    }
  }

  ::v-deep {
    .ant-form-explain,
    .ant-form-extra {
      height: 21px;
      min-height: 21px;
    }

    .ant-form-item-control {
      width: 100%;
      line-height: 36px;
    }
  }
  ::v-deep .mce-tinymce {
    box-shadow: none;
    border-radius: 2px;
    border: 1px solid rgba(215, 224, 239, 1) !important;
  }
}
// 详情显示
.detail-content {
  padding-top: 15px;
}

.detail-item {
  position: relative;
  margin-bottom: 25px;
  padding-left: 75px;
  min-height: 22px;
  &-label,
  &-val {
    width: 100%;
    font-size: 14px;
    line-height: 1.5;
    color: #666;
  }
  &-label {
    position: absolute;
    left: 0;
    top: 0;
    color: #333;
    width: 75px;
    font-weight: bold;
  }
}

@media (max-width: 1600px) {
  .detail-content {
    padding-top: 5px;
    padding-bottom: 10px;
  }
  .detail-item {
    min-height: 22px;
    margin-bottom: 5px;
  }
  .edit-action {
    padding: 10px 20px;
  }
}
</style>


